package controllers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"github.com/gorilla/websocket"
	"github.com/parnurzeal/gorequest"
	"log"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"
	"unicode"
	"unicode/utf8"
)

type ApiUserStatusController struct {
	baseController
}

/*
* 账号封禁状态
 */
func (c *ApiUserStatusController) StatusLimit1() {

	cookie := c.GetString("cookie")
	// 初始化请求
	request := gorequest.New()

	//获取修改密码页面
	_, body, errs := request.Get("https://passport.baidu.com/v2/accountsecurity").
		Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.514.1919.810 Safari/537.36").
		Set("Referer", "https://pan.baidu.com").
		Set("Cookie", cookie).
		End()
	if errs != nil {
		fmt.Println(errs)
		c.respOut("已掉线")
		return
	}

	index := strings.Index(body, "Pass.bdstoken")
	if index < 0 {
		fmt.Println("bdstoken not found in the string.")
		c.respOut("已掉线")
		return
	}

	var info BaiDuInfo

	//获取登录状态
	_, body, errs = request.Get("https://pan.baidu.com/api/loginStatus?clienttype=0&app_id=250528&web=1").
		Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.514.1919.810 Safari/537.36").
		Set("Referer", "https://pan.baidu.com").
		Set("Cookie", cookie).
		End()
	if errs != nil {
		fmt.Println(errs)
		c.respOut("已掉线")
		return
	}

	// 使用json.Unmarshal函数将字符串解析到person变量中
	err := json.Unmarshal([]byte(body), &info)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		c.respOut("已掉线")
		return
	}

	userStatus := "异常"
	if info.Errno == 0 {
		userStatus = "正常"
		//if info.LoginInfo.Username == "" {
		//	userName1 := UserName(cookie)
		//	//这个接口用户名称也是空那就正常
		//	if userName1 != info.LoginInfo.Username {
		//		userStatus = "异常"
		//	}
		//}
		//infoStr := fmt.Sprintf("%s", userStatus)
		//c.respOut(infoStr)
	} else if info.Errno == -6 {
		c.respOut("已掉线")
		return
	} else {
		c.respOut("未知错误")
		return
	}

	//获取网盘数据
	listurl := "https://pan.baidu.com/api/list?order=name&desc=1&showempty=0&web=1&page=1&num=100&dir=%2F&t=0.58745665736407491&channel=chunlei&web=1&app_id=250528&bdstoken=" + info.LoginInfo.Bdstoken + "&clienttype=0"
	_, body, errs = request.Get(listurl).
		Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.514.1919.810 Safari/537.36").
		Set("Referer", "https://pan.baidu.com").
		Set("Cookie", cookie).
		End()
	if errs != nil {
		c.respOut("已掉线")
		return
	}

	var panInfo BaiDuInfo
	// 使用json.Unmarshal函数将字符串解析到person变量中
	err = json.Unmarshal([]byte(body), &panInfo)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		c.respOut("已掉线")
		return
	}

	if userStatus == "正常" || userStatus == "异常" {
		// 如果登录状态正常，网盘列表打不开表示异常
		if panInfo.Errno == 0 {
			userStatus = "正常"
			infoStr := fmt.Sprintf("%s", userStatus)
			c.respOut(infoStr)
		} else if panInfo.Errno == -6 {
			c.respOut("异常")
		} else {
			c.respOut("异常")
		}
	}

}

type LoginStatus struct {
	Errno     int `json:"errno"`
	LoginInfo struct {
		Bdstoken    string `json:"bdstoken"`
		PhotoURL    string `json:"photo_url"`
		Svip10ID    string `json:"svip10_id"`
		Uk          int64  `json:"uk"`
		UkStr       string `json:"uk_str"`
		Username    string `json:"username"`
		VipIdentity string `json:"vip_identity"`
		VipLevel    int    `json:"vip_level"`
		VipPoint    int    `json:"vip_point"`
		VipType     string `json:"vip_type"`
	} `json:"login_info"`
	Newno     string `json:"newno"`
	RequestID int64  `json:"request_id"`
	ShowMsg   string `json:"show_msg"`
}

type CreateReq struct {
	Deviceid  string `json:"deviceid"`
	AppKey    string `json:"appKey"`
	Token     string `json:"token"`
	Crminfo   string `json:"crminfo"`
	FromPage  string `json:"fromPage"`
	FromType  string `json:"fromType"`
	Foreignid string `json:"foreignid"`
}

type CreateResp struct {
	Code int `json:"code"`
	Info struct {
		Accid    string   `json:"accid"`
		Exchange []string `json:"exchange"`
		Storage  struct {
		} `json:"storage"`
		Bid   string `json:"bid"`
		Token string `json:"token"`
	} `json:"info"`
}

type MsgResp struct {
	Key  int           `json:"key"`
	Ser  int           `json:"ser"`
	Sid  int           `json:"sid"`
	Cid  int           `json:"cid"`
	Code int           `json:"code"`
	R    []interface{} `json:"r"`
}

type CmdMsgResp struct {
	Cmd            int `json:"cmd"`
	DelayReplyTime int `json:"delayReplyTime"`
	ExtendInfo     struct {
		DialogID       string `json:"dialogId"`
		FlowID         string `json:"flowId"`
		Message        string `json:"message"`
		NeedStatistics bool   `json:"needStatistics"`
		NodeID         string `json:"nodeId"`
		NodeType       string `json:"nodeType"`
		PreRequestID   string `json:"preRequestId"`
		RequestID      string `json:"requestId"`
		SendType       int    `json:"sendType"`
		ShowUseful     bool   `json:"showUseful"`
		SubType        string `json:"subType"`
	} `json:"extendInfo"`
	Template struct {
		Unions []struct {
			Type   string `json:"type"`
			Detail struct {
				Style  string `json:"style"`
				Label  string `json:"label"`
				Params string `json:"params"`
				Type   string `json:"type"`
				Target string `json:"target"`
			} `json:"detail,omitempty"`
		} `json:"unions"`
		ID      string `json:"id"`
		Version string `json:"version"`
	} `json:"template"`
	TransferRgType int    `json:"transferRgType"`
	Type           string `json:"type"`
}

type CmdMsgReq10 struct {
	Target   string `json:"target"`
	Params   string `json:"params"`
	Template struct {
		ID    string `json:"id"`
		Label string `json:"label"`
	} `json:"template"`
	Cmd int `json:"cmd"`
}

/*
* 账号封禁状态
 */
func (c *ApiUserStatusController) StatusLimit() {

	cookie := c.GetString("cookie")
	//提取cookie
	cookieList := strings.Split(cookie, "----")
	if len(cookieList) == 1 {
		cookie = cookieList[0]
	} else {
		cookie = cookieList[len(cookieList)-1]
	}

	// 初始化请求
	request := gorequest.New()

	_, body, errs := request.Get("https://pan.baidu.com/api/loginStatus?clienttype=0&app_id=250528&web=1&channel=chunlei&version=1732497980559").
		Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.514.1919.810 Safari/537.36").
		Set("Referer", "https://pan.baidu.com").
		Set("Cookie", cookie).
		End()
	if errs != nil {
		fmt.Println(errs)
		c.respOut("已掉线")
		return
	}
	var info LoginStatus
	// 使用json.Unmarshal函数将字符串解析到person变量中
	err := json.Unmarshal([]byte(body), &info)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		c.respOut("已掉线")
		return
	}

	createReq := CreateReq{
		Deviceid:  info.LoginInfo.UkStr,
		AppKey:    "bce4a79234a6210aba6aaa60293a9322",
		Token:     "ifwmvrvduwcxy2td3iv2",
		Crminfo:   "[{\"key\":\"real_name\",\"value\":\"x\"},{\"key\":\"avatar\",\"label\":\"头像\",\"value\":\"https://himg.bdimg.com/sys/portrait/item/public.1.3f45313c.mgSHzf2ozseiOMel5zHUiw.jpg\"},{\"key\":\"version\",\"label\":\"版本\",\"value\":\"0.0.0\"},{\"key\":\"from\",\"label\":\"来源\",\"value\":\"default_default\"},{\"key\":\"client\",\"label\":\"端类型\",\"value\":\"web\"},{\"key\":\"username\",\"label\":\"用户昵称\",\"value\":\"anyone137\"},{\"key\":\"viptype\",\"label\":\"会员类型\",\"value\":\"0\"},{\"key\":\"channel\",\"label\":\"设备信息\",\"value\":\"default\"},{\"key\":\"devicename\",\"label\":\"设备名称\",\"value\":\"default\"},{\"key\":\"useragent\",\"label\":\"浏览器信息\",\"value\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36\"},{\"key\":\"date\",\"label\":\"上报时间\",\"value\":1732345146081},{\"key\":\"referrer\",\"label\":\"客服配置referrer\",\"value\":\"https://pan.baidu.com/icsweb\"},{\"key\":\"robotId\",\"label\":\"客服配置robotId\",\"value\":\"7\"},{\"key\":\"devuid\",\"label\":\"百度ID\",\"value\":\"default\"},{\"key\":\"CUID\",\"label\":\"百度cuid\",\"value\":\"default\"},{\"key\":\"source\",\"label\":\"场景\",\"value\":\"default\"},{\"key\":\"Recording\",\"label\":\"截图录屏幕\"}]",
		FromPage:  "https://pan.baidu.com/icsweb",
		FromType:  "web",
		Foreignid: info.LoginInfo.UkStr,
	}

	url1 := "https://visit.pan-ics.com/webapi/user/create.action?appKey=bce4a79234a6210aba6aaa60293a9322"
	_, body, errs = request.Post(url1).
		Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.514.1919.810 Safari/537.36").
		Set("Referer", "https://pan.baidu.com").
		Set("Cookie", cookie).
		Send(&createReq).
		End()

	var createResp CreateResp
	err = json.Unmarshal([]byte(body), &createResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		c.respOut("已掉线")
		return
	}

	if createResp.Info.Accid == "" {
		c.respOut("已掉线")
		return
	}

	_, body, errs = request.Get("https://link.pan-ics.com/socket.io/1/?t="+fmt.Sprintf("%d", time.Now().UnixMilli())).
		Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.514.1919.810 Safari/537.36").
		Set("Referer", "https://pan.baidu.com").
		Set("Cookie", cookie).
		End()
	if errs != nil {
		fmt.Println(errs)
		c.respOut("已掉线")
		return
	}

	parts := strings.Split(body, ":")
	fmt.Printf("socket-id: %s\n", parts[0])

	serverURL := "wss://link.pan-ics.com/socket.io/1/websocket/" + parts[0]

	// 解析 WebSocket 服务器 URL
	u, err := url.Parse(serverURL)
	if err != nil {
		log.Fatal("Failed to parse URL:", err)
	}

	// 创建 WebSocket 连接拨号器
	dialer := websocket.Dialer{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		//Subprotocols:    []string{"echo"}, // 可选：指定子协议
	}

	// 连接到 WebSocket 服务器
	header := http.Header{}
	header.Set("Host", "link.pan-ics.com")
	header.Set("Origin", "https://visit.pan-ics.com")
	header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")

	conn, _, err := dialer.Dial(u.String(), header)
	if err != nil {
		log.Fatal("Failed to connect to WebSocket server:", err)
	}
	defer conn.Close()
	ser := 1
	//done := make(chan struct{})
	done := make(chan int)

	var readCount float64 = 0

	var maxReceived int = 15
	var dateString string
	// 读取消息
	go func() {
		defer close(done)

		sendAccErrMsg := false
		for {
			_, message, err := conn.ReadMessage()
			if err != nil {
				log.Println("Read error:", err)
				return
			}
			msgg := string(message)

			fmt.Printf("Received: %s\n", msgg)
			//最大收取15条消息
			maxReceived--

			msglist := strings.Split(msgg, ":::")
			if len(msglist) > 1 {
				var msgresp MsgResp
				err = json.Unmarshal([]byte(msglist[1]), &msgresp)
				if err != nil {
					fmt.Println("Error parsing JSON:", err)
					c.respOut("已掉线")
					return
				}

				if msgresp.R != nil && len(msgresp.R) > 1 {
					value, ok := msgresp.R[0].(float64)
					if ok {
						fmt.Println("serverid=", value)
						readCount = value

						ser++
						msg := "3:::{\"SID\":4,\"CID\":5,\"SER\":%d,\"Q\":[{\"t\":\"byte\",\"v\":7},{\"t\":\"byte\",\"v\":3},{\"t\":\"LongArray\",\"v\":[\"%d\"]}]}"
						sendmsg(conn, fmt.Sprintf(msg, ser, int64(readCount)))

						//收到登录消息在送
						if !sendAccErrMsg {
							//发送账号检查消息
							uuid4 := strings.Replace(uuid.NewString(), "-", "", -1)
							ser++
							msg = "3:::{\"SID\":101,\"CID\":1,\"SER\":%s,\"Q\":[{\"t\":\"Property\",\"v\":{\"0\":0,\"1\":\"-1\",\"8\":0,\"9\":\"账号使用功能异常\",\"11\":\"%s\",\"13\":0,\"14\":%s,\"105\":1}}]}"
							sendmsg(conn, fmt.Sprintf(msg, strconv.Itoa(ser), uuid4, fmt.Sprintf("%d", time.Now().UnixMilli())))
							sendAccErrMsg = true
						}
					}
				}

				//测试消息
				//msgg = "\\\"preRequestId\\\"核实到您的账号违反网盘用户协议，因此部分功能被限制使用，限制开始时间为2024-12-14 15:31:45。建议您根据页面提示，在手机端使用手机号码+验证码的方式登录后申诉验证解除，72小时后再操作即可。"
				//收到消息
				if strings.Index(msgg, "\\\"preRequestId\\\"") > -1 {
					if strings.Index(msgg, "功能被限制使用") > -1 {
						dateString = extractDateChars(msgg)

						if dateString != "" {
							//timeStr1 := "2023-10-05T14:04:00Z" // 示例时间字符串（RFC3339格式）
							//timeFormat1 := time.RFC3339          // 时间格式
							timeFormat := time.DateTime // 时间格式 2020-10-11 12:12:14

							// 解析时间字符串
							parsedTime, err := time.Parse(timeFormat, dateString)
							if err != nil {
								fmt.Println("解析时间字符串时出错:", err)
								return
							}

							// 获取当前时间
							currentTime, _ := time.Parse(timeFormat, "2016-07-30 08:30:05")
							// 比较时间
							if parsedTime.After(currentTime) {
								fmt.Println("解析的时间大于当前时间")
								done <- 0
								break
							} else {
								fmt.Println("解析的时间小于或等于当前时间")
								uuid4 := strings.Replace(uuid.NewString(), "-", "", -1)
								ser++
								msg := "3:::{\"SID\":101,\"CID\":1,\"SER\":%s,\"Q\":[{\"t\":\"Property\",\"v\":{\"0\":0,\"1\":\"-1\",\"8\":0,\"9\":\"下载异常\",\"11\":\"%s\",\"13\":0,\"14\":%s,\"105\":1}}]}"
								sendmsg(conn, fmt.Sprintf(msg, strconv.Itoa(ser), uuid4, fmt.Sprintf("%d", time.Now().UnixMilli())))
							}
						}

					} else if strings.Index(msgg, "暂时无法为您手动解封") > -1 {
						done <- 0
						break
					} else {
						//1 状态正常
						done <- 1
						break
					}
				}

				//兜底超次数避免死循环
				if maxReceived < 0 {
					done <- 1
					break
				}

				/* 正常账号需要点击 ，异常的直接就返回了
				if strings.Index(msgg, "账号使用功能异常") > -1 {
					cmdReq10, _ := parseSysmsg(msgresp)
					if cmdReq10 != "" {
						ser++

						msg := "3:::{\"SID\":101,\"CID\":1,\"SER\":%s,\"Q\":[{\"t\":\"Property\",\"v\":{\"0\":0,\"1\":\"-1\",\"8\":100,\"10\":\"%s\",\"11\":\"%s\",\"13\":0,\"14\":%s,\"105\":1}}]}"
						uuid := strings.Replace(uuid.NewString(), "-", "", -1)

						//加引号编码
						cmdReq10 = strings.Replace(cmdReq10, "\"", "\\\"", -1)
						msg = fmt.Sprintf(msg, strconv.Itoa(ser), cmdReq10, uuid, fmt.Sprintf("%d", time.Now().UnixMilli()))
						//替换引号空格
						msg = ReplacelineCode(msg)
						//生成出来格式化的
						//msg = "3:::{\"SID\":101,\"CID\":1,\"SER\":19,\"Q\":[{\"t\":\"Property\",\"v\":{\"0\":0,\"1\":\"-1\",\"8\":100,\"10\":\"{\\\"target\\\":\\\"968D9CF7259747A2-cd1fcf3cb217a53f\\\",\\\"params\\\":\\\"_preRequestId=1b233829-7c55-47d1-860b-7ed5cbf7ae8c&_sessionId=4313253&_preNodeId=968D9CF7259747A2-3a482e03971fba55&_token=29be41511cd24944a205c4c065c6d8a3&_flowId=968D9CF7259747A2-1B373287B4A0564E\\\",\\\"template\\\":{\\\"id\\\":\\\"qiyu_template_text\\\",\\\"label\\\":\\\"账号使用功能异常\\\"},\\\"cmd\\\":202}\",\"11\":\"ed562cb651934c568b406114376725a9\",\"13\":0,\"14\":1732842365982,\"105\":1}}]}"
						sendmsg(conn, msg)
					}
				}*/

			}

		}
	}()

	//登录操作
	appkey := "bce4a79234a6210aba6aaa60293a9322"
	uuid2 := strings.Replace(uuid.NewString(), "-", "", -1)
	uuid3 := strings.Replace(uuid.NewString(), "-", "", -1)
	// 发送消息
	login := "3:::{\"SID\":2,\"CID\":3,\"SER\":" + strconv.Itoa(ser) + ",\"Q\":[{\"t\":\"Property\",\"v\":{\"4\":\"Windows 10 64-bit\",\"6\":27,\"9\":1," +
		"\"13\":\"" + uuid2 + "\"," +
		"\"18\":\"" + appkey + "\"," +
		"\"19\":\"" + createResp.Info.Accid + "\"," +
		"\"24\":\"Chrome 123.0.0.0\"," +
		"\"26\":\"" + uuid3 + "\"," +
		"\"1000\":\"" + createResp.Info.Token + "\"}}]}"
	sendmsg(conn, login)
	msg := ""

	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()

	interrupt := make(chan os.Signal, 1)

	for {
		select {
		case v, ok := <-done:
			if !ok {
				fmt.Println("Channel已关闭")
				return
			}
			if v == 1 {
				c.respOut("正常")
			} else {
				//c.respOut("异常<br/>" + dateString)
				fmt.Println("异常<br/>" + dateString)
				c.respOut("异常")
			}
			return
		case t := <-ticker.C:
			//5秒超时退出
			log.Println("write:" + t.String() + msg)
			c.respOut("正常")
			return
			//同步信息
			//msg = "3:::{\"SID\":5,\"CID\":1,\"SER\":2,\"Q\":[{\"t\":\"Property\",\"v\":{\"1\":0,\"2\":0,\"14\":0,\"16\":0,\"17\":0,\"100\":0}}]}"
			//sendmsg(conn, msg)

		case <-interrupt:
			log.Println("interrupt")

			err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				log.Println("write close:", err)
				return
			}
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			return
		}
	}
}

// extractChineseChars 提取字符串中的中文字符
func extractChineseChars(s string) string {
	var builder strings.Builder
	for i, w := 0, 0; i < len(s); i += w {
		runeValue, width := utf8.DecodeRuneInString(s[i:])
		if unicode.Is(unicode.Han, runeValue) {
			// 如果是中文字符，则追加到构建器中
			builder.WriteRune(runeValue)
		}
		w = width
	}
	return builder.String()
}

// 提取日期类型
func extractDateChars(s string) string {
	// 定义正则表达式模式，匹配时间格式 "2006-01-02 15:04:05"
	re := regexp.MustCompile(`\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}`)

	// 查找匹配项
	matches := re.FindString(s)

	// 输出匹配到的时间字符串
	if matches != "" {
		fmt.Println("提取到的时间字符:", matches)
	} else {
		fmt.Println("未找到匹配的时间字符。")
	}
	return matches
}

func ReplacelineCode(msg string) string {
	msg = strings.ReplaceAll(msg, "\r", "")
	msg = strings.ReplaceAll(msg, "\n", "")
	msg = strings.ReplaceAll(msg, "\t", "")
	return msg
}

// ToJson 对象转json字符串
func ToJson(obj interface{}) (str string, err error) {
	//会导致字符转义，如 将&变成了\u0026
	//buf, err := json.Marshal(obj)

	//转成json 不转义特殊字符
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	err1 := jsonEncoder.Encode(obj)
	if err != nil {
		fmt.Println(err)
		return "", err1
	}
	//字节码转字符串
	str = bf.String()
	return str, nil
}

func isMap(v interface{}) bool {
	// 获取值的反射类型
	t := reflect.TypeOf(v)
	// 判断类型是否是 Map
	return t.Kind() == reflect.Map
}

func parseSysmsg(msgresp MsgResp) (string, error) {

	if !(msgresp.Sid == 4 && msgresp.Cid == 1) {
		return "", nil
	}

	if msgresp.R != nil && len(msgresp.R) >= 2 {

		// 使用类型断言将 interface{} 转换为 map[string]interface{}
		if m, ok := msgresp.R[1].(map[string]interface{}); ok {
			// 类型断言成功，m 现在是一个 map[string]interface{} 类型的变量

			if m1, ok1 := m["body"].([]interface{}); ok1 {
				if m1 != nil && len(m1) > 0 {
					if m2, ok2 := m1[0].(map[string]interface{}); ok2 {
						fmt.Println(m2["10"])
						cmdString, exists := m2["10"].(string)
						if exists {
							var cmdMsgResp CmdMsgResp
							err := json.Unmarshal([]byte(cmdString), &cmdMsgResp)
							if err != nil {
								fmt.Println("Error parsing JSON:", err)
								return "", err
							}
							var cmdReq10 CmdMsgReq10
							for _, v := range cmdMsgResp.Template.Unions {
								if strings.Index(v.Detail.Label, "账号使用功能异常") > -1 {
									cmdReq10.Cmd = 202
									cmdReq10.Template.ID = "qiyu_template_text"
									cmdReq10.Template.Label = "账号使用功能异常"
									cmdReq10.Target = v.Detail.Target
									cmdReq10.Params = v.Detail.Params

									return ToJson(cmdReq10)
								}
							}
						}
					}
				}

				//// 你可以像操作普通的 map 一样操作 m
				//name, exists := m["body"].(string)
				//if exists {
				//	fmt.Println("Name:", name)
				//} else {
				//	fmt.Println("Name key does not exist or is not a string")
				//}
			}
		}
	}
	return "", nil
}

func sendmsg(conn *websocket.Conn, msg string) {
	fmt.Println(msg)
	err := conn.WriteMessage(websocket.TextMessage, []byte(msg))
	if err != nil {
		log.Println("Write error:", err)
		return
	}
}

func (c *ApiUserStatusController) respOut(status string) {
	c.Ctx.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	c.Ctx.WriteString(status)
}
